package com.atguigu.chapter08;

import com.atguigu.bean.OrderEvent;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/6/16 15:08
 */
public class Flink05_High_Order {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        // 创建WatermarkStrategy
        WatermarkStrategy<OrderEvent> wms = WatermarkStrategy
            .<OrderEvent>forBoundedOutOfOrderness(Duration.ofSeconds(20))
            .withTimestampAssigner(new SerializableTimestampAssigner<OrderEvent>() {
                @Override
                public long extractTimestamp(OrderEvent element, long recordTimestamp) {
                    return element.getEventTime();
                }
            });
        env
            .readTextFile("input/OrderLog.csv")
            .map(line -> {
                String[] datas = line.split(",");
                return new OrderEvent(
                    Long.valueOf(datas[0]),
                    datas[1],
                    datas[2],
                    Long.parseLong(datas[3]) * 1000);
                
            })
            .assignTimestampsAndWatermarks(wms)
            .keyBy(OrderEvent::getOrderId)
            .process(new KeyedProcessFunction<Long, OrderEvent, String>() {
                
                private ValueState<OrderEvent> payState;
                private ValueState<OrderEvent> createState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    payState = getRuntimeContext().getState(new ValueStateDescriptor<OrderEvent>("payState", OrderEvent.class));
                    createState = getRuntimeContext().getState(new ValueStateDescriptor<OrderEvent>("createState", OrderEvent.class));
                }
    
                @Override
                public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                    // 定时器触发表示只有一个
                    if(createState.value() !=null){
                        out.collect(createState.value().getOrderId() + " 只有创建订单没有支付订单....");
                    }else{
                        out.collect(payState.value().getOrderId() + " 只有支付没有创建, 检测系统漏洞....");
                    }
                }
    
                @Override
                public void processElement(OrderEvent event, // id是1
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    // 处理只有一个状态的情况
                    // 每个key的第一条数据过来的 时候, 注册定时器
                    if (payState.value() == null && createState.value() == null) {
                        // 这个key的第一条 注册定时器
                        ctx.timerService().registerEventTimeTimer(event.getEventTime() + 50 * 60 * 1000);
                    } else {
                        // 这个key的第二条 删除定时器
                        OrderEvent oe = payState.value() == null ? createState.value() : payState.value();
                        ctx.timerService().deleteEventTimeTimer(oe.getEventTime() + 50 * 60 * 1000);
                    }
                    
                    /*
                        如果这次是pay, 应该去状态中查找是否有对应的create, 如果有正常
                        如果没有 把这个pay信息存储到状态中
                        
                        create同样的操作
                     */
                    String type = event.getEventType();
                    if ("create".equals(type)) {
                        if (payState.value() == null) {
                            // pay还没有来
                            createState.update(event);
                            
                        } else if (payState.value().getEventTime() - event.getEventTime() <= 45 * 60 * 1000) {
                            out.collect(event.getOrderId() + "正常创建和支付..");
                        } else {
                            out.collect(event.getOrderId() + "被超时支付, 请检查系统是否有漏洞..");
                        }
                    } else if ("pay".equals(type)) {
                        if (createState.value() == null) {
                            payState.update(event);
                            
                        } else if (event.getEventTime() - createState.value().getEventTime() <= 45 * 60 * 1000) {
                            out.collect(event.getOrderId() + "正常创建和支付..");
                        } else {
                            out.collect(event.getOrderId() + "被超时支付, 请检查系统是否有漏洞..");
                        }
                    }
                }
            })
            .print();
        
        env.execute();
        
    }
}
